<template>
  <el-upload
    ref="upload"
    class="file-upload"
    style="display:inline-block;margin-left:10px;"
    :disabled="!!percent"
    :action="action"
    :headers="headers"
    :on-progress="uploadProgress"
    :on-error="uploadError"
    :on-success="uploadSuccess"
    :show-file-list="false"
  >
    <el-button
      :size="buttonSize"
      type="primary"
      :loading="!!percent"
    >{{ !!percent ? `${percent}%` : '点击上传' }}</el-button>
  </el-upload>
</template>
<script>
import { getToken } from '@/utils/auth';
export default {
  name: 'Upload',
  props: {
    url: {
      type: String,
      default: '/dfile/file/upload'
    },
    buttonSize: {
      type: String,
      default: 'small'
    }
  },
  data() {
    return {
      percent: 0,
      action: process.env.VUE_APP_BASE_API + this.url,
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  methods: {
    uploadProgress(e, file) {
      this.percent = parseInt(e.percent);
      if (e.percent === 100) {
        setTimeout(() => {
          this.percent = 0;
        }, 800);
      }
    },
    uploadSuccess(response, file) {
      if (response.status === 200) {
        this.$emit('on-success', response, file);
      } else {
        this.uploadError();
      }
    },
    uploadError() {
      this.percent = 0;
      this.notifiyError('上传失败');
    },
    uploadAbort() {
      this.$refs.upload.abort();
      this.percent = 0;
    }
  }
};
</script>
